<template>
    <div class="orgStructrue">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline" @submit.native.prevent>
            <el-form-item prop="orgIds">
                <tree-select
                class="self-org-tree2"
                v-model="searchForm.orgIds"
                filterable
                :width="200"
                :data="orgOptions"
                :defaultProps="orgDefaultProps"
                :checkedKeys="defaultCheckedCategoryIds"
                :nodeKey="orgNodeKey">
                </tree-select>
            </el-form-item>
            <el-form-item>
                <el-input v-model="searchForm.name" auto-complete="off" placeholder="请输入用户名/账号/手机号" clearable @keyup.enter.native="search"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button class="form-search-btn" type="primary" @click="search">搜索</el-button>
            </el-form-item>
            <el-form-item>
                <el-switch
                    v-model="searchForm.selectAllChildFlg"
                    active-value="0"
                    inactive-value="1"
                    @change="searchForm.selectAllChildFlg == 0 ? showChildText = '显示下级组织人员' : showChildText = '不显示下级组织人员'">
                </el-switch>
                <span :class="{'color-4': searchForm.selectAllChildFlg == 0, 'color-8': searchForm.selectAllChildFlg == 1}">{{ showChildText }}</span>
            </el-form-item>
        </el-form>
        
        <div class="more-btns">
            <el-button type="primary" @click="orgTreeDialogVisible = true">组织结构图</el-button>
            <el-button type="primary" @click="addDialogVisible1">新增组织部门</el-button>
            <el-button type="primary" @click="dialogVisible">分配用户</el-button>
        </div>
        <el-container style="height: 700px; border: 1px solid #eee">
            <el-aside width="500px">
                <p>组织部门树结构</p>
                <el-tree
                    v-if="loadTree"
                    :data="treeData"
                    node-key="id"
                    highlight-current
                    default-expand-all
                    :expand-on-click-node="false"
                    @node-click="handleTreeNodeClick"
                    :props="defaultProps"
                    :current-node-key="selectBuildNodeId"
                    ref="orgTree">
                    <span class="custom-tree-node" slot-scope="{ node, data }">
                        <span>{{ node.label }}</span>
                        <span>
                            <el-button @click="handleEdit(node, data)" type="text" size="small">编辑</el-button>
                            <el-button @click="handleDelete(node, data)" type="text" size="small">删除</el-button>
                        </span>
                    </span>
                </el-tree>
            </el-aside>
            <el-container>
                <el-main>
                    <el-table
                    :data="tableData"
                    style="width: 99.9%"
                    >
                        <el-table-column
                            label="序号"
                            type="index" width="100px">
                        </el-table-column>
                        <el-table-column 
                        prop="name" 
                        label="姓名" >
                            <!-- 图片的显示 -->
                        </el-table-column>
                        <el-table-column
                            prop="accountName"
                            label="用户账号">
                        </el-table-column>
                        <el-table-column
                            prop="phone"
                            label="移动电话">
                        </el-table-column>
                        <el-table-column
                            prop="postName"
                            label="职位">
                        </el-table-column>
                        <el-table-column
                            prop="roleNames"
                            label="角色">
                        </el-table-column>
                        <el-table-column
                            prop="departmentName"
                            label="所属组织部门">
                        </el-table-column>
                        <el-table-column
                            label="操作">
                            <template slot-scope="scope">
                                <el-button @click="deleteUser(scope.row)" type="text" size="small">移除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-pagination
                    background
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[10, 50, 100]"
                    :page-size="10"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
                    </el-pagination>
                </el-main>
            </el-container>
        </el-container>
        <!-- 新增组织部门 -->
        <el-dialog
            :close-on-click-modal="false"
            title="新增组织部门"
            v-if="addDialogVisible"
            :visible.sync="addDialogVisible"
            width="35%"
            class="addzuzhi">
            <el-form type="flex" :model="savedepart" class="" @submit.native.prevent>
                <el-form-item >
                    <label style="color:red;">*</label>
                    <label>名称：</label>
                    <el-input v-model="savedepart.name" placeholder="填写名称" style="width:80%;float:right"></el-input>
                </el-form-item>
                <el-form-item>
                    <label style="color:red;">*</label>
                    <label>所属组织单位：</label>
                    <tree-select
                    class="self-org-tree1"
                    v-model="searchForm.orgIds"
                    :disabled="true"
                    filterable
                    :width="480"
                    :data="orgOptions"
                    :defaultProps="orgDefaultProps"
                    :checkedKeys="defaultCheckedCategoryId3"
                    :nodeKey="orgNodeKey">
                    </tree-select>
                </el-form-item> 
                <el-form-item>
                    <label>上级组织部门：</label>
                    <tree-select
                    class="form-item-tree-select"
                    v-model="savedepart.department"
                    placeholder="请选择部门"
                    filterable
                    :width="480"
                    :data="treeData"
                    :defaultProps="defaultProps"
                    :checkedKeys="defaultCheckedCategoryId4"
                    :nodeKey="typeNodeKey">
                    </tree-select>
                </el-form-item> 
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="clearDept">取 消</el-button>
                <el-button type="primary" @click="savedepartment">保 存 </el-button>
            </span>
        </el-dialog>
        <!-- 分配用户 -->
        <el-dialog
            :close-on-click-modal="false"
            title="添加用户"
            v-if="DialogVisible"
            :visible.sync="DialogVisible"
            width="35%">
            <el-form type="flex" :model="addUsers" class="" @submit.native.prevent>
                <el-form-item>
                    <label>所属组织部门：</label>
                    <tree-select
                    class="add-user-form-item-tree-select"
                    v-model="addUsers.orgId"
                    placeholder="请选择部门"
                    filterable
                    :class="addUsers"
                    :width="480"
                    :data="treeData"
                    :defaultProps="defaultProps"
                    :checkedKeys="defaultCheckedCategoryIds2"
                    :nodeKey="typeNodeKey">
                    </tree-select>
                </el-form-item>
                <el-form-item>
                    <label style="color:red;">*</label>
                    <label>添加用户：</label>
                    <el-select class="adduser" :filter-method="dataFilter" filterable v-model="addUsers.user" multiple  placeholder="请选择，可以多选" style="width:80%;float:right">
                    <el-option
                    v-for="item in userinfoList"
                    :key="item.name"
                    :label="item.name"
                    :value="item.accountName">
                    </el-option>
                    <el-pagination
		  	  		    @current-change="handleCurrentChange1"
                        :current-page.sync="currentPage1"   
		  	  		    small
		  	  		    layout="total, prev, pager, next"
		  	  		    :total="addTotal">
	  	  		    </el-pagination>
                    </el-select>
                    
                </el-form-item> 
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cacleAddUser">取 消</el-button>
                <el-button type="primary" @click="addListUser()">添 加 </el-button>
            </span>
        </el-dialog>
        <!-- 编辑组织结构 -->
        <el-dialog
            :close-on-click-modal="false"
            title="编辑组织部门"
            v-if="updateDialogVisible"
            :visible.sync="updateDialogVisible"
            width="35%">
            <el-form type="flex" :model="savedepart" class="" @submit.native.prevent>
                <el-form-item>
                    <label style="color:red;">*</label>
                    <label>名称：</label>
                    <el-input v-model="savedepart.name" placeholder="填写名称" style="width:80%;float:right"></el-input>
                </el-form-item>
                <el-form-item>
                    <label style="color:red;">*</label>
                    <label>所属组织单位：</label>
                    <tree-select
                    class="self-org-tree1"
                    :disabled="true"
                    v-model="searchForm.orgId"
                    filterable
                    :width="480"
                    :data="orgOptions"
                    :defaultProps="orgDefaultProps"
                    :checkedKeys="defaultCheckedCategoryId"
                    :nodeKey="orgNodeKey">
                    </tree-select>
                </el-form-item> 
                <el-form-item>
                    <label style="color:red;">*</label>
                    <label>上级组织部门：</label>
                    <tree-select
                        class="add-user-form-item-tree-select1"
                        v-model="savedepart.department"
                        placeholder="请选择部门"
                        filterable
                        :width="480"
                        :data="treeData1"
                        :defaultProps="defaultProps"
                        :checkedKeys="defaultCheckedCategoryId1"
                        :nodeKey="typeNodeKey">
                    </tree-select>
                </el-form-item> 
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="clearDept">取 消</el-button>
                <el-button type="primary" @click="savedepartment">保 存 </el-button>
            </span>
        </el-dialog>
        <!-- 组织部门树形结构图 -->
        <el-dialog
            :close-on-click-modal="false"
            title="组织结构图"
            v-if="orgTreeDialogVisible"
            :visible.sync="orgTreeDialogVisible"
            width="90%">
            <org-tree :orgId="searchForm.orgIds || $store.state.userinfo.org.id" :orgIds="searchForm.orgIds || $store.state.userinfo.organizationIds"></org-tree>
        </el-dialog>
    </div>
</template>
<script>
import { getOrgList} from '@/api/org'
import { getDepartmentTree,deleteDepartment,getDepartmentUserList,deleteUserFromDepartment,saveDepartment,addUserOnDepartment} from '@/api/rdLearnOrg'
import TreeSelect from '@/libs/TreeSelect/Main'
import { getUcOrgList,getUserList } from '@/api/sysConfig'
import OrgTree from './Dialog/OrgTree'

export default {
    components: { 
        TreeSelect,
        OrgTree
    },
    data() {
        return {
            multipleSelection: [],//被选中的行
            learnTime:30,//学习时长
            detailsList:[],//资料详情
            orgOptions: [],//单位下拉框
            treeData:[],//组织部门树结构
            treeData1:[],//编辑树结构列表
            selectBuildNodeId: '', // 当前选择的节点Id
            loadTree: false,
            addTitle:'',
            defaultProps: {
                children: 'nodes',
                label: 'name',
                value: 'id'
            },
            typeNodeKey: 'id',
            defaultCheckedCategoryId: [],
            defaultCheckedCategoryIds: [],
            addDialogVisible:false,//新增组织部门结构弹窗
            DialogVisible:false,//分配用户
            updateDialogVisible:false,//编辑组织结构
            tableData:[],//用户列表
            isMuilUnitUser:this.$store.state.userinfo.isMuilUnitUser,
            //搜索
            searchForm: {
                orgIds:'',
                orgId:''/*this.$store.state.userinfo.org.id*/,
                name: '',
                department:'',
                selectAllChildFlg: '0'
            },
            showChildText: '显示下级组织人员',
            //新增
            savedepart: {
                id:'',
                orgId:''/*this.$store.state.userinfo.org.id*/,
                name: '',
                department:''
            },
            userinfoList:[],//新增用户下拉框列表
            addUsers:{
                orgId:'',
                user:'',
            },
            // 分页
            currentPage: 1,
            currentPage1: 1,
            pageSize: 10,
            total: 0,
            addTotal:0, //添加用户的数据总数
            departmentId:'',
            orgDefaultProps: {
                children: 'nodes',
                label: 'name',
                value: 'id'
            },
            defaultCheckedCategoryId1:[],
            defaultCheckedCategoryIds2:[],
            defaultCheckedCategoryId3:[],
            defaultCheckedCategoryId4:[],
            checkedOrgKeys: [],
            orgNodeKey: 'id',
            // 组织树弹框
            orgTreeDialogVisible: false
        }
    },
    created() {
        let that = this
        that.getTreeList();
        that.getOrgList()
        //that.getDepartmentUserList();
    },
    methods: {
        getOrgList() {
            let that = this
            let newArr = []
            getUcOrgList({
                type: 1
            }).then(res => {
                newArr = res.data
                that.orgOptions = newArr
                that.$nextTick(() => {
                    // 默认选中全部
                    that.searchForm.orgIds = newArr[0].id
                    that.defaultCheckedCategoryIds = String(newArr[0].id).split(',')
                })
            })
        },
        //搜索
        search(){
            let that = this;
            that.getDepartmentUserList();
        },
        //获取用户列表
        getDepartmentUserList(departmentId,pageIndex, pageSize){
            let that = this;
            if (pageIndex) {
                that.currentPage = pageIndex
            }
            if (pageSize) {
                that.pageSize = pageSize
            }
            let parames={
                queryType: 1,
                pageIndex: that.currentPage - 1,
                pageSize:that.pageSize,
                name: that.searchForm.name || '',
                orgIds:that.searchForm.orgIds || '',
                departmentId: departmentId || that.departmentId || 1,
                selectAllChildFlg: that.searchForm.selectAllChildFlg
            }
            getDepartmentUserList(parames).then(res => {
                that.tableData = res.data;
                if(departmentId){
                    that.$nextTick(() => {
                        that.defaultCheckedCategoryIds2 = String(departmentId).split(',')
                        that.defaultCheckedCategoryId = String(departmentId).split(',')
                        that.defaultCheckedCategoryId4 = String(departmentId).split(',')
                    })
                }
                
                that.total = res.total
            })
        },
        //删除
        deleteUser(res){
            let that = this
            that.$confirm('移除用户后，用户仍然存在，但会从所在组织部门中被移除。确定从组织部门中移除该用户吗？', '移除', {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning',
            roundButton: true
            }).then(() => {
            //删除接口 
                let parames={
                    departmentId:res.departmentId,
                    userAccount: res.accountName,
                } 
                deleteUserFromDepartment(parames).then(res => {
                    if(res.status === 200) {
                        that.$message({
                            message: '删除成功！',
                            type: 'success'
                        })
                    }
                    
                })
                // 刷新页面
                that.getDepartmentUserList(res.departmentId);
            }).catch(() => {
            })
        },
        //获取树列表
        getTreeList(){
            let that = this;
            that.loadTree =true;
            let parames={
                orgId: that.searchForm.orgIds || that.$store.state.userinfo.org.id,
                orgIds: that.searchForm.orgIds || that.$store.state.userinfo.organizationIds,
            }
            getDepartmentTree(parames).then(res => {
                that.treeData = res.data;
                if(res.data[0]){
                    that.departmentId = res.data[0].id
                    that.selectBuildNodeId = res.data[0].id
                }
            })
        },
        //编辑树列表
        getTreeList1(node, data){
            let that = this;
            let parames={
                orgId: that.searchForm.orgIds || this.$store.state.userinfo.org.id,
                orgIds: that.searchForm.orgIds || that.$store.state.userinfo.organizationIds,
                unCheckId: data.id  || ''
            }
            getDepartmentTree(parames).then(res => {
                that.treeData1 = res.data;
                that.$nextTick(() => {
                    that.updateDialogVisible = true;
                    that.savedepart.name = node.label;
                    that.searchForm.orgId = data.orgId
                    that.selectBuildNodeId = data.id
                    that.defaultCheckedCategoryId= String(data.orgId).split(',')
                    that.savedepart.id = data.id
                    //新增部门
                    if(node.parent.key){
                        that.savedepart.department = node.parent.key
                        that.defaultCheckedCategoryId1 = String(node.parent.key).split(',')
                    }else{
                        that.savedepart.department = ''
                        that.defaultCheckedCategoryId1 = []
                    }
                    //添加部门编辑时不可选状态
                    setTimeout(() => {
                        let $arr = $('.add-user-form-item-tree-select1').find('div[aria-disabled]').find('.el-tree-node__label')
                        for(var j=0; j < $arr.length; j++) {
                            $($arr[j]).addClass('is-disabled')
                        }
                    }, 200)
                    
                })
                
            })
        },
        //添加人员获取人员列表
        addUser(name,currentPage1){
            let that = this;
            let parames = {
                name: name ||　'',
                pageIndex : that.currentPage1 - 1,
                pageSize : that.pageSize,
                orgId : that.searchForm.orgIds || this.$store.state.userinfo.org.id,
                roleIds : '',
                queryType:1
            }
            getUserList(parames).then(res => {
                that.userinfoList = res.data
                that.addTotal = res.total
            })
        },
        dataFilter(val){
            this.addUser(val, this.pageSize)
        },
        dialogVisible(){
            let that = this
            that.DialogVisible =true
        },
        // 编辑
        handleEdit(node, data) {
            event.stopPropagation()
            let that = this
            that.getTreeList1(node, data)
        },
        //新增组织部门
        addDialogVisible1(){
            let that = this;
            that.savedepart.department = that.$refs.orgTree.getCurrentKey() || ''
            that.savedepart.name = ''
            that.addDialogVisible = true;
            that.defaultCheckedCategoryId3 = String(that.searchForm.orgIds).split(',')
        },
        // 删除
        handleDelete(node, data) {
            // 阻止事件冒泡
            event.stopPropagation()
            let that = this
            if(data) {
                this.$confirm('删除当前节点后，其子节点同时会被删除，并且不可恢复。是否确定删除当前节点？', '提示', {
                    confirmButtonText: '删除',
                    cancelButtonText: '取消',
                    type: 'warning',
                    roundButton: true
                }).then(() => {
                    deleteDepartment({
                        departmentId: node.key,
                    }).then(res => {
                        if(res.status === 200) {
                            that.$message({
                                message: '删除成功！',
                                type: 'success'
                            })
                            // 刷新页面
                            if(node.key == that.selectBuildNodeId){
                                that.getTreeList()
                                setTimeout(() => {
                                    that.getDepartmentUserList(that.selectBuildNodeId)
                                },1000)
                            }else{
                                that.getTreeList()
                            }
                        } else {
                            that.$message({
                                message: res.info,
                                type: 'warning'
                            })
                        }
                    })
                    // 阻止事件冒泡
                    event.stopPropagation()
                }).catch(() => {

                })     
            }
        },
        // 树型节点被点击
        handleTreeNodeClick(obj, node, item) {
            let that = this;
            that.selectBuildNodeId = obj.id
            that.departmentId = obj.id
            that.addUser.orgId = obj.id
            that.addUsers.orgId = obj.name
            //新增组织带入组织名
            that.savedepart.department= obj.id
            that.getDepartmentUserList(obj.id)
        },
        handleCurrentChange(currentPage) {
            this.getDepartmentUserList(this.departmentId,currentPage)
        },
        handleCurrentChange1(currentPage1) {
            this.addUser($('.adduser .el-select__input')._value, this.pageSize)
        },
        handleSizeChange(pageSize) {
            this.getDepartmentUserList(this.departmentId,1,pageSize)
        },
        //新增弹窗确认关闭
        handleClose(done) {
            let that = this
            that.$confirm('确认关闭？')
            .then(_ => {
                done();
                
            })
            .catch(_ => {});
        },
        //新增组织部门
        savedepartment(){
            let that = this;
            let parames = {
                id:that.savedepart.id || '',
                orgId:that.searchForm.orgIds,
                name:that.savedepart.name,
                parentId:that.savedepart.department,

            }
            saveDepartment(parames).then(res => {
                if(res.status==200){
                    that.$message({
                        message: '保存成功！',
                        type: 'success'
                    })
                    that.getTreeList();
                    that.addDialogVisible=false; 
                    that.updateDialogVisible = false;
                    that.savedepart.id = ''
                }
            })
            that.clearDept()
        },
        cacleAddUser(){
            let that = this;
            // that.orgId='',
            // that.user='',
            //that.defaultCheckedCategoryId = []
            that.DialogVisible = false
            that.addUsers={};
        },
        clearDept(){
            let that = this;
            that.savedepart.id = ''
            // that.savedepart.orgId = ''
            that.savedepart.name = ''
            // that.savedepart.department = ''
            //that.defaultCheckedCategoryId = []
            that.addDialogVisible = false;
            that.updateDialogVisible=false;
        },
        //新增人员
        addListUser(){
            let that = this;
            let arrList = [];
            for(var i = 0;i< that.addUsers.user.length;i++){
                let hwy = {
                    departmentId:String(that.defaultCheckedCategoryIds2),
                    userAccount:that.addUsers.user[i],
                    orgId:that.searchForm.orgIds || this.$store.state.userinfo.org.id,
                }
                arrList.push(hwy)
            }
            let parames = {
                userList:JSON.stringify(arrList),
                // departmentId:that.addUsers.orgId,
                // userAccount:JSON.stringify(that.addUsers.user),
                // orgId:that.searchForm.orgId || this.$store.state.userinfo.org.id,
            }
            addUserOnDepartment(parames).then(res => {
                that.$message({
                    message: '保存成功！',
                    type: 'success'
                })
                that.getDepartmentUserList(String(that.defaultCheckedCategoryIds2));
                that.DialogVisible=false; 
            })
            //that.addUsers={};
            that.cacleAddUser()
        }
    },
    watch: {
        scoreTypeSelect(val, oldVal) {
            if(val !== oldVal) {
                this.addUser()
            }
        },
        orgIdsSelect(val, oldVal) {
            if(val && val !== oldVal) {
                this.search()
                this.getTreeList()
            }
        },
        orgIdSelect(val, oldVal) {
            if(val && val !== oldVal) {
                this.getTreeList()
            }
        },
        selectAllChildFlg(val, oldVal) {
            if(val && val !== oldVal) {
                this.search()
            }
        }
    },
    computed: { 
        scoreTypeSelect() {
            return this.addUsers.orgId
        },
        orgIdsSelect() {
            return this.searchForm.orgIds
        },
        orgIdSelect() {
            return this.searchForm.orgId
        },
        selectAllChildFlg() {
            return this.searchForm.selectAllChildFlg
        }
    }
}
</script>
<style lang="scss" scoped>
    .custom-tree-node {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        padding-right: 8px;
    }
</style>
<style lang="scss">
    .orgStructrue{
        .form-item-tree-select {
            .tree-select {
                float: right;
                margin-top: -40px;
                margin-left: 10px;
            }
        }
        .self-org-tree1{
            .tree-select {
                float: right;
                margin-top: -40px;
                margin-left: 10px;
            }
        }
        .add-user-form-item-tree-select {
            .tree-select {
                float: right;
                margin-top: -40px;
                margin-left: 23px;
            }
        }
        .add-user-form-item-tree-select1 {
            .tree-select {
                float: right;
                margin-top: -40px;
                margin-left: 23px;
            }
        }
        .el-main{
            padding: 0px 0px 0px 30px;
        }
    }
    .add-user-form-item-tree-select1{
        .el-tree .is-disabled {
            color: #c0c4cc;
            cursor: not-allowed;
        }
    }
        /* .tree-select{
            margin-left: 10px;
            width: 505px !important;
        } */
</style>